package org.flexlancer.Logger
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import mx.controls.Alert;
	
	import org.flexlancer.utils.Path;
	
	public class Logger
	{
		public static var log_flag:String = LogFlags.IN_FILE;
		public static var err_flag:String = LogFlags.IN_ALERT;
		public static var log_file_name:String = "";
		
		public static function Log(msg:String):void{
			try{
				DisplayMessege(BuildMessege(msg),log_flag);
			}catch(err:Error){
				trace("Error in Logger");
			}
		}
		public static function LogE(err:Error,msg:String = ""):void{
			try{
				var send_msg:String = "-----* EXCEPTION *-----\n";
				if ( msg != "" ){
					send_msg += "{"+msg+"}";
				}
				send_msg+= err.message+"\n"+err.getStackTrace();
				DisplayMessege(BuildMessege(send_msg),err_flag);
				
				if ( err_flag != LogFlags.IN_FILE)
					DisplayMessege(BuildMessege(send_msg),LogFlags.IN_FILE);
			}catch(err:Error){
				trace("Error in Logger");
			}
		}
		private static function BuildMessege(msg:String):String{
			try{
				var dtNow:Date = new Date();
				var dispMsg:String = "["+dtNow.toString()+"] "+msg;
				return dispMsg;
			}catch(err:Error){
				trace("Error in BuildMessege");
			}
			return "";
		}
		private static function DisplayMessege(msg:String,flags:String):void{
			try{
				switch(flags){
					case LogFlags.IN_TRACE:
						trace(msg);
						break;
					case LogFlags.IN_FILE:
						if ( log_file_name == "" ) 
							log_file_name = "AIR.log";
							
						var file:File = File.documentsDirectory.resolvePath(Path.Combine("BENAROUS/LOGS",log_file_name));
						var fs:FileStream = new FileStream();
						fs.open(file,FileMode.APPEND);
						fs.writeMultiByte(msg+"\r\n","iso-8859-1");
						fs.close();
						break;
					case LogFlags.IN_ALERT:
						Alert.show(msg);
						break;
					default:
					break;
				}
			}catch(err:Error){
				trace("Error in DisplayMessege");
			}
		}
	}
}